package com.imooc.bilibili.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class JsonHttpMessageConverterConfig {

    /**
     * HttpMessageConverters  对数据或者请求对json一个转换的工具类
     * @return
     */
    @Bean
    @Primary
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,//对json格式进行格式化
                SerializerFeature.WriteNullStringAsEmpty,//将value为null的字段转成空字符串
                SerializerFeature.WriteNullListAsEmpty,//将value为null的list转成一个空的list
                SerializerFeature.WriteMapNullValue,//作用同上
                SerializerFeature.MapSortField,//key-value升序排序
                SerializerFeature.DisableCircularReferenceDetect//禁用循环引用,得到正确的Json格式
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastConverter);
    }
}
